/**
 * 微信工具包 v2版本
 * 请勿修改此处代码，因为插件更新后此处代码会被覆盖。
 * 作者：VK
 */
const crypto = require("crypto");

var wxpay = {};

/**
 * 获取请求的xml
 * @param {String} method 方法名
 * @param {Object} params 参数
 * @param {Object} config 配置
 */
wxpay.getXML = function(method, params, config) {
  let signParams = Object.assign({
    mch_appid: config.appId,
    mchid: config.mchId
  }, params);
  signParams = JSON.parse(JSON.stringify(signParams));
  const str = wxpay.getSignStr(signParams) + '&key=' + config.key;
  let sign = wxpay.md5(str).toUpperCase();
  signParams.sign = sign;
  let xmlStr = wxpay.buildXML(signParams);
  //console.log(1,signParams);
  //console.log(2,xml);
  return xmlStr;
};


wxpay.getSignStr = function(obj) {
  return Object.keys(obj)
    .filter(key => key !== 'sign' && obj[key] !== undefined && obj[key] !== '')
    .sort()
    .map(key => key + '=' + obj[key])
    .join('&')
};


wxpay.md5 = function(str, encoding = 'utf8') {
  return crypto
    .createHash('md5')
    .update(str, encoding)
    .digest('hex')
};
// 简易版Object转XML，只可在微信支付时使用，不支持嵌套
wxpay.buildXML = function(obj, rootName = 'xml') {
  const content = Object.keys(obj).map(item => {
    if (wxpay.isPlainObject(obj[item])) {
      return `<${item}><![CDATA[${JSON.stringify(obj[item])}]]></${item}>`
    } else {
      return `<${item}><![CDATA[${obj[item]}]]></${item}>`
    }
  })
  return `<${rootName}>${content.join('')}</${rootName}>`
};

wxpay.isPlainObject = function(obj) {
  return Object.prototype.toString.call(obj) === '[object Object]';
};
// 简易版XML转Object，只可在微信支付时使用，不支持嵌套
wxpay.parseXML = function(xml) {
  const xmlReg = /<(?:xml|root).*?>([\s|\S]*)<\/(?:xml|root)>/
  const str = xmlReg.exec(xml)[1]
  const obj = {}
  const nodeReg = /<(.*?)>(?:<!\[CDATA\[){0,1}(.*?)(?:\]\]>){0,1}<\/.*?>/g
  let matches = null
  // eslint-disable-next-line no-cond-assign
  while ((matches = nodeReg.exec(str))) {
    obj[matches[1]] = matches[2]
  }
  return obj
};




module.exports = wxpay;
